import useExpose from '@/hooks/useExpose'
import Tools from './components/Tools'
import { computed, defineComponent, PropType, reactive, Ref, ref, watch } from 'vue'

export interface ITableExpose {
  table: Ref;
  handleResetFn: Function;
}

const defaultPagination = () => ({
  total: 0,
  pageSize: 10,
  current: 1,
  showQuickJumper: true,
  showSizeChanger: true,
  showTotal: (total: number, range: number[]) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条'
  }
})

export default defineComponent({
  name: 'MsTable',
  props: {
    resetFn: {
      type: Function as PropType<Function>,
      default: null
    },
    page: {
      type: Number as PropType<number>,
      default: 0
    },
    limit: {
      type: Number as PropType<number>,
      default: 0
    },
    dataSource: {
      type: Array as PropType<Array<any>>,
      default: () => ([])
    },
    columns: {
      type: Array as PropType<Array<any>>,
      default: () => []
    },
    rowKey: {
      type: String as PropType<string>,
      default: 'id'
    },
    total: {
      type: Number as PropType<number>,
      default: 0
    },
    pagination: {
      type: [Object, Boolean] as PropType<boolean | any>,
      default: () => defaultPagination()
    },
    loadingTable: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    exportName: {
      type: String as PropType<string>,
      default: '表格数据'
    }
  },
  emits: ['update:page', 'update:limit'],
  setup(props, { slots, emit }) {
    const table = ref<any>(null)
    const state = reactive({
      myPagination: Object.assign(props.pagination, { total: computed(() => props.total), pageSize: computed(() => props.limit) }),
      cacheColumns: props.columns
    })

    const toolsFilter = (filter: Array<string>) => {
      state.cacheColumns = props.columns.filter((item) => filter.includes(item.dataIndex || item.slots?.customRender))
    }

    watch(() => state.myPagination.current, (val) => emit('update:page', val))
    watch(() => state.myPagination.pageSize, (val) => emit('update:limit', val))

    useExpose({
      table,
      handleResetFn: () => {
        state.myPagination = defaultPagination()
      }
    })

    return () => {
      return (
        <>
          <Tools columns={props.columns} exportName={props.exportName} onFilter={toolsFilter} />
          <a-spin spinning={props.loadingTable}>
            <a-table
              ref={table}
              v-slots={slots}
              columns={state.cacheColumns}
              dataSource={props.dataSource}
              pagination={state.myPagination}
              onChange={(config: any) => { state.myPagination = config }}
              row-key="userId"
            />
          </a-spin>
        </>
      )
    }
  }
})
